package com.damagedboy.pocketbook.web.config;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "myFilter", urlPatterns = "/*")
public class MyFilter implements Filter {

    @Override
    public void destroy() {
        System.out.println("过滤器销毁");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rep = (HttpServletResponse) response;
        Object adminusersession = req.getSession().getAttribute("adminusersession");
        String requestURI = req.getRequestURI();
        if (requestURI.contains("/login") || requestURI.contains("/nopermission")) {
            chain.doFilter(request, response);
        } else {
            if (adminusersession == null) {
                req.getRequestDispatcher("/admin/nopermission").forward(req, rep);
            }
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println("过滤器初始化");
    }

}